import {
  getAgentPage,
  deleteAgent,
  getAgent,
  getAgentNew,
  resetPassword
} from '~/services/api/menber'
import Toast from 'tdesign-miniprogram/toast/index';
Page({
  /** 
   * 页面的初始数据 
   */
  data: {
    userPhone: '',
    goodsListLoadStatus: 0,
    breadMenu: [],
    showBread: false,
    pageLoading: false,
    isActive: null,
    layout: 0,
    sorts: '',
    userId: '',
    overall: 1,
    show: false,
    visible: false,
    searchName: "",
    minVal: '',
    maxVal: '',
    hasLoaded: false,
    loadMoreStatus: 0,
    loading: true,
    listTitles: [],
    fixedTitle: null,
    toView: 'inToView0',
    oHeight: [],
    scroolHeight: 0,
    userList: [],
    pullDownRefreshing: false,
    emptyImg: 'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    options: [{
        label: '正式代理商',
        value: 2
      },
      {
        label: '意向代理商',
        value: 1,
      },
      {
        label: '咨询代理商',
        value: 0
      },
    ],
  },
  goodListPagination: {
    pageNo: 1,
    pageSize: 10,
  },
  add() {
    wx.navigateTo({
      url: '/subpages/pages/addNewAgent/addNewAgent?isAdd=1',
    })
  },
  onLoad: function (options) {
    var that = this;
    let role = wx.getStorageSync('rlole');
    this.setData({
      userId: role.userId
    })
    // that.getList();
    this.loadHomePage()
  },
  toDetail(e) {
    wx.navigateTo({
      url: `/subpages/pages/addNewAgent/addNewAgent?isEdit=true&kid=${e.currentTarget.dataset.group.kid}`,
    })
  },


  async getList(id) {
    const role = wx.getStorageSync('role');
    const userId = role?.userId;
    let {
      data
    } = await getAgentPage({
      pageNo: 1,
      pageSize: 10,
      param: {
        parentAgentUserId: userId,
        userName: this.data.userName,
      }
    });
    console.log(data.entitiess)
    this.setData({
      userList: data.entities
    })
  },

  searchFn() {
    this.setData({
      visible: true
    })
  },
  onChange(e) {
    this.setData({
      'agentType': e.detail.value,
    });
  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
    })
  },
  navSub(e) {
    let index = e.currentTarget.dataset.index;
    if (index == 0) {
      // 显示初始化列表
      this.setData({
        breadMenu: []
      });
      this.getBrands();
      return;
    } else {
      this.setData({
        breadMenu: this.data.breadMenu.slice(0, index + 1)
      });
    }
    this.getBrands(this.data.breadMenu[index].kid);
  },
  getNext(e) {
    console.log(111);
    let breadMenu = this.data.breadMenu;
    breadMenu.push(e.currentTarget.dataset.group)
    this.setData({
      showBread: true,
      breadMenu
    });
    this.getBrands(e.currentTarget.dataset.group.kid);
  },
  async resetPassword(e) {
    let {
      data
    } = await resetPassword({
      kid: e.currentTarget.dataset.group.kid
    });
    console.log(data);
    if (data) {
      console.log(111);
      Toast({
        selector: '#t-toast',
        message: '重置密码成功',
        icon: '',
        duration: 1000,
      });
    }
  },
  async getBrands(id) {
    const role = wx.getStorageSync('role');
    const userId = role?.userId;
    let {
      data
    } = await getAgentNew({
      "param": {
        parentAgentUserId: id || userId
      },
      pageSize: 10,
      pageNo: 1
    });
    this.setData({
      userList: data.entities
    })
  },
  onInputChange(e) {
    const key = e.currentTarget.dataset.key,
      value = e.detail.value;
    this.setData({
      [key]: value
    })
  },
  confirm() {
    // this.getList();
    this.setData({
      visible: false
    })
    this.loadGoodsList(true)
  },
  reset() {
    this.setData({
      visible: false,
      agentType: '',
      userName: "",
      empUserName: '',
      userPhone: ""
    })
    this.loadGoodsList(true)
  },

  async onDelete(e) {
    // 操作类型 1删除,2启用，3禁用，4上架，5下架
    let group = e.currentTarget.dataset.group;
    let res = await deleteAgent({
      kid: group.kid,
      opType: 1
    });
    let index = this.data.userList.findIndex((el) => el.kid == group.kid);
    if (res.code == '200') {
      Toast({
        selector: '#t-toast',
        message: '删除成功',
        icon: '',
        duration: 1000,
      });
      let data =
        this.data.userList.splice(index, 1);
      this.setData({
        userList: this.data.userList
      })
    }
  },
  navterminal(e) {
    let group = e.currentTarget.dataset.group;
    wx.navigateTo({
      url: `/subpages/pages/terminalCount/visitorRecord?kid=${group.kid}`,
    })
  },
  async onForbiden(e) {
    // 操作类型 1删除,2启用，3禁用，4上架，5下架
    let group = e.currentTarget.dataset.group;
    let index = this.data.userList.findIndex((el) => el.kid == group.kid);
    let res = await deleteAgent({
      kid: group.kid,
      opType: group.enableFlag == 1 ? 3 : 2
    });
    if (res.code == '200') {
      Toast({
        selector: '#t-toast',
        message: '操作成功',
        icon: '',
        duration: 1000,
      });
      let data =
        this.data.userList.splice(index, 1, {
          ...group,
          enableFlag: group.enableFlag == 1 ? 0 : 1
        });
      this.setData({
        userList: this.data.userList
      })

    }
  },
  navToTerminal(e) {
    wx.navigateTo({
      url: `/subpages/pages/allTerminal/allTerminal?agentUserId=${e.currentTarget.dataset.group.kid}`,
    });
  },
  navToContact(e) {
    wx.navigateTo({
      url: `/subpages/pages/contactor/contactor?agentUserId=${e.currentTarget.dataset.group.kid}`,
    })
  },

  navToSaleOrder(e) {
    wx.navigateTo({
      url: `/subpages/pages/saleOrder/saleOrder?orderId=${e.currentTarget.dataset.group.kid}`,
    })
  },


  loadHomePage() {
    wx.stopPullDownRefresh();
    this.setData({
      pageLoading: true,
    });
    this.loadGoodsList(true);
  },
  onPullDownRefresh() {
    this.loadHomePage();
  },
  onReTry() {
    this.loadGoodsList();
  },
  submit() {
    this.loadGoodsList(true)
  },
  clearContent() {
    this.setData({
      userName: "",
      breadMenu: []
    }, () => {
      this.loadGoodsList(true)
    })
  },
  async loadGoodsList(fresh = false) {
    const role = wx.getStorageSync('role');
    const userId = role?.userId;
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
      this.setData({
        pageLoading: false,
      });
    }
    this.setData({
      goodsListLoadStatus: 1
    });
    const pageSize = this.goodListPagination.pageSize;
    let pageIndex = this.goodListPagination.pageNo + 1;
    if (fresh) {
      pageIndex = 1;
    }
    try {
      const {
        data
      } = await getAgentPage({
        "pageNo": pageIndex,
        "pageSize": pageSize,
        param: {
          parentAgentUserId: userId,
          userName: this.data.userName,
        }
      });
      this.setData({
        userList: fresh ? data.entities : this.data.userList.concat(data.entities),
        goodsListLoadStatus: pageIndex == 1 && data.entities.length < 10 ? 2 : data.entities > 1 ? 0 : 2,
      });

      this.goodListPagination.pageSize = data.pageSize;
      this.goodListPagination.pageNo = data.pageNo;
    } catch (err) {
      this.setData({
        goodsListLoadStatus: 3
      });
    }
  },

  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },
})